package seiacpjava_a2.utilities;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;

public class BinarySearchTreeFileGenerator {
	
	public static void main(String[] args) {

		int size = 1000;
		int[] input = null;
		String filePath = "c:/comp6411_files/bst_inefficient_inputfile_1000Items.txt";
		
//		input = generateInefficientTreeInput(size);
		input = generateUniqueSortedInput(1000, 2000);
//		System.out.println(input);
//		System.out.println(Arrays.toString(input));
		writeToFile(mkString(input), filePath);
		System.out.println("Finished writing file " + filePath);
	}
	
	private static int[] generateInefficientTreeInput(int size) {
		int[] input = new int[size];
		
		for(int i = 0 ; i < size ;i ++)
			input[i] = i+1;
		return input;
	}
	
	private static int[] generateEfficientTreeInput(int size, int maxValue) {
		int[] input = generateUniqueSortedInput(size, maxValue);
		
		return input;
	}
	
	private static int[] generateUniqueSortedInput(int size, int maxValue) {
		Random randomNumberGenerator = new Random();
		int[] input = new int[size];
		int random = -1;
		Set<Integer> hashSet = new HashSet<>();
		
		for(int i=0 ; i< size ; i++ ){
			random = randomNumberGenerator.nextInt(maxValue);
			if(hashSet.contains(random)) {
				do {
					random = randomNumberGenerator.nextInt(maxValue);
				} while (hashSet.contains(random));
				hashSet.add(random);
			} else {
				hashSet.add(random);
			}
			input[i] = random;
		}		
		Arrays.sort(input);
		return input;
	}
	
	private static String mkString(int[] input) {
		StringBuilder builder = new StringBuilder("");
		for(int i = 0 ; i<input.length ; i++) {
			if (i == (input.length - 1))
				builder.append(input[i]);
			else
				builder.append(input[i]+",");
		}
		return builder.toString();
	}
	

	private static void writeToFile(String output, String filePath) {
		try {
			// Create file
			FileWriter fstream = new FileWriter(filePath);
			BufferedWriter out = new BufferedWriter(fstream);
			out.write(output);
			// Close the output stream
			out.close();
		} catch (Exception e) {// Catch exception if any
			System.err.println("Error: " + e.getMessage());
		}
	}
	
}
